package task

import (
	"apibe/grpc/rome/v1/share/logger"
	"io"
	"os/exec"
	"strings"
)

func asyncLog(reader io.ReadCloser) error {
	cache := ""
	buf := make([]byte, 1024, 1024)
	for {
		num, err := reader.Read(buf)
		if err != nil {
			if err == io.EOF || strings.Contains(err.Error(), "closed") {
				err = nil
			}
			return err
		}
		if num > 0 {
			oByte := buf[:num]
			oSlice := strings.Split(string(oByte), "\n")
			line := strings.Join(oSlice[:len(oSlice)-1], "\n")
			logger.Logger.Infof("%s%s\n", cache, line)
			cache = oSlice[len(oSlice)-1]
		}
	}
}

func execute(path string) {
	cmd := exec.Command("sh", "-c", path)

	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()

	if err := cmd.Start(); err != nil {
		logger.Logger.Errorf("Error starting command: %s......", err.Error())
		return
	}

	go asyncLog(stdout)
	go asyncLog(stderr)

	if err := cmd.Wait(); err != nil {
		logger.Logger.Errorf("Error waiting for command execution: %s......", err.Error())
		return
	}
}
